package com.hopedove.workshop.viewmodel

import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.hopedove.net.ApiCallResult
import com.hopedove.repository.CommonRepository
import com.hopedove.utils.LoginValidation
import com.hopedove.utils.LoginValidationResult
import com.hopedove.utils.toMd5
import com.hopedove.viewmodel.BaseViewModel
import com.hopedove.workshop.api.WorkshopApi
import com.hopedove.workshop.repository.WorkshopUserRepository
import com.hopedove.workshop.ui.WorkshopHomeActivity
import kotlinx.coroutines.launch

class WorkshopLoginViewModel(
    private val api: WorkshopApi,
    private val loginValidation: LoginValidation,
    private val userRepo: WorkshopUserRepository,
    private val commonRepo: CommonRepository
) : BaseViewModel() {

    val username = ObservableField<String>()
    val password = ObservableField<String>()

    fun onLogin() {
        login()
    }

    private fun login() = viewModelScope.launch {
        startLoading()

        when (val result = loginValidation.validate(username.get(), password.get())) {
            is LoginValidationResult.Failed -> {
                _toastText.value = result.message
            }
            is LoginValidationResult.Ok -> {
                val name = username.get()!!
                val pwd = password.get()!!
                when (val apiResult = api.login(name, pwd.toMd5())) {
                    is ApiCallResult.Success -> {
                        commonRepo.getServerDateTime(true)
                        userRepo.userLogin(apiResult.data!!)
                        _navigation.value = WorkshopHomeActivity::class.java
                    }
                    is ApiCallResult.Error -> _toastText.value = apiResult.error
                }
            }
        }
    }.invokeOnCompletion { dismissLoading() }

}